<?php

namespace App\Http\Controllers\Admin;

use App\Repositories\Permission\AdminRepository;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inertia\Response;

class AuthController extends Controller
{
    protected array $validateRules = [
        'phone' => 'required|string|regex:/^1[34578]\d{9}$/',
        'captcha' => 'required|captcha',
        'password' => ['required', 'string', 'min:6', 'max:16', 'regex:/^(?=.*[A-Za-z])(?=.*\d).+$/'],
    ];
    protected array $validateMessages = [
        'phone.required' => '请输入手机号',
        'phone.regex' => '请输入正确的手机号',
        'captcha.required' => '请输入图形验证码',
        'captcha.captcha' => '请输入正确的图形验证码',
        'password.required' => '请输入密码',
        'password.min' => '密码长度不能小于6',
        'password.max' => '密码长度不能大于16',
        'password.regex' => '密码必须包含字母和数字',
    ];

    public function login(): Response|RedirectResponse
    {
        if(auth()->guard('admin')->check()){
            return redirect()->route('admin.dashboard.workplace');
        }
        return $this->inertia('auth/index');
    }

    public function authenticate(Request $request, AdminRepository $adminRepository): RedirectResponse
    {
        $throttleKey = Str::transliterate(Str::lower($request->input('phone')) . '|' . $request->ip());
        if (RateLimiter::tooManyAttempts($throttleKey, 5)) {
            $seconds = RateLimiter::availableIn($throttleKey);
            return back()->withErrors([
                'phone' => '登录失败次数过多，请 '.$seconds.' 秒后再试'
            ]);
        }

        try {
            $params = $this->validate($request, $this->validateRules, $this->validateMessages);
        } catch (ValidationException $e) {
            return back()->withErrors($e->errors());
        }

        $admin = $adminRepository->findByPhone($params['phone']);
        // 合并用户不存在和密码错误的提示
        if (!$admin || !Hash::check($params['password'], $admin->password)) {
            // 登录失败时增加尝试计数
            RateLimiter::hit($throttleKey, 1800);

            // 计算剩余尝试次数
            $attempts = RateLimiter::attempts($throttleKey);
            $remaining = 5 - $attempts;

            $errorMsg = '账号或密码不正确';
            // 添加剩余尝试次数提示
            if ($remaining > 0) {
                $errorMsg .= "（剩余 {$remaining} 次尝试）";
            } else {
                $errorMsg .= "（账号已锁定）";
            }
            return back()->withErrors([
                'phone' => $errorMsg,
            ]);
        }

        // 登录成功时清除登录限制
        RateLimiter::clear($throttleKey);
        auth('admin')->login($admin, $request->boolean('remember'));
        $request->session()->regenerate();
        return redirect()->route('admin.dashboard.workplace');
    }

    public function logout(Request $request): RedirectResponse
    {
        auth()->guard('admin')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect()->route('admin.login');
    }
}
